<?
include("inc_security.php");

//Call class menu
$menu				= new menu();
$listAll			= $menu->getAllChild("categories_multi", "cat_id", "cat_parent_id", 0, "cat_type='product' AND cat_id IN (" . $fs_category . ") AND lang_id = " . $lang_id, "cat_id,cat_name,cat_type,cat_all_child", "cat_order ASC,cat_name ASC", "cat_has_child", 0);
unset($menu);

//Khai báo biến khi hiển thị danh sách
$fs_title		= $module_name . " quá " . $maxLastUpdate . " ngày chưa cập nhật";
$fs_action		= getURL(0,0,1,1,"record_id");
$fs_redirect	= getURL(0,0,1,1,"record_id|r") . "&r=" . random();
$fs_errorMsg	= "";
$fs_alertMsg	= "";

/*****----- Quick Edit -----*****/
$action			= getValue("action", "str", "POST", "");
if($action == "quick_edit"){
	
	//Get data edit
	$arrRecord	= getValue("record_id", "arr", "POST", "");
	if(is_array($arrRecord)){
		
		foreach($arrRecord as $value){
			
			$fs_errorMsg	= "";
			
			$record_id		= intval($value);
			if($record_id <= 0) continue;
			
			$db_edit			= new db_query("SELECT * FROM " . $fs_table . " WHERE " . $id_field . " = " . $record_id . " AND lang_id = " . $lang_id);
			if(mysql_num_rows($db_edit->result) == 0){
				$fs_errorMsg .= "&bull; Không tìm thấy dữ liệu, bạn hãy liên hệ với ban quản trị Website!<br />";
			}
			else{
		
				$edit				= mysql_fetch_assoc($db_edit->result);
				unset($db_edit);
				
				//Lấy dữ liệu đề giữ nguyên trạng thái khi submit error
				$pro_category_id		= getValue("pro_category_id" . $record_id, "int", "POST", $edit["pro_category_id"]);
				$pro_name				= getValue("pro_name" . $record_id, "str", "POST", $edit["pro_name"]);
				$pro_price				= getValue("pro_price" . $record_id, "dbl", "POST", $edit["pro_price"]);
				$pro_unit				= getValue("pro_unit" . $record_id, "str", "POST", $edit["pro_unit"]);
				$pro_last_update		= time();
				
				// Check xem category có tồn tại hay ko
				$db_check			= new db_query("SELECT cat_id FROM categories_multi WHERE cat_type = 'product' AND cat_id = " . $pro_category_id);
				if(mysql_num_rows($db_check->result) == 0){
					$fs_errorMsg	.= "&bull; Danh mục bạn chọn không tồn tại.<br />";
				}
				$db_check->close();
				unset($db_check);
					
				/*
				Call class form:
				1). Ten truong
				2). Ten form
				3). Kieu du lieu , 0 : string , 1 : kieu int, 2 : kieu email, 3 : kieu double, 4 : kieu hash password
				4). Noi luu giu data  0 : post, 1 : variable
				5). Gia tri mac dinh, neu require thi phai lon hon hoac bang default
				6). Du lieu nay co can thiet hay khong
				7). Loi dua ra man hinh
				8). Chi co duy nhat trong database
				9). Loi dua ra man hinh neu co duplicate
				*/
				$myform = new generate_form();
				//Add table insert data
				$myform->addTable($fs_table);
				if(strpos($fs_category, $pro_category_id . ",") === false){
					$fs_errorMsg .= "&bull; Bạn không được phép truy cập category này!<br />";
				}
				$myform->add("pro_category_id", "pro_category_id", 1, 1, 1, 1, "Bạn chưa chọn danh mục.", 0, "");
				$myform->add("pro_name", "pro_name", 0, 1, " ", 1, "Bạn chưa nhập tên sản phẩm.", 0, "");
				//$myform->add("pro_price", "pro_price", 3, 1, 0, 0, "", 0, "");
				$myform->add("pro_unit", "pro_unit", 0, 1, "", 0, "", 0, "");
				$myform->add("pro_last_update", "pro_last_update", 1, 1, 0, 0, "", 0, "");
				
				//Check form data
				$fs_errorMsg .= $myform->checkdata();
				
				if($fs_errorMsg == ""){
					
					//Update to database
					$myform->removeHTML(0);
					$db_update = new db_execute($myform->generate_update_SQL($id_field, $record_id));
					unset($db_update);
					
				}//End if($fs_errorMsg == "")
				else{
					$fs_alertMsg .= "- Bạn không thay đổi được sản phẩm có ID = " . $record_id . ".\\n";
				}
				
				unset($myform);
			
			}
			
		}// End foreach($arrRecord as $value)
		
		//Nếu có data nào bị lỗi thì hiển thị thông báo alert message error rồi redirect
		if($fs_alertMsg != ""){
			echo '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">';
			echo '<script language="javascript">alert("Có những lỗi sau:\\n' . $fs_alertMsg . '");</script>';
		}
		
		// Redirect
		redirect($fs_redirect);
		
	}// End if(is_array($arrRecord))
	
}
/*****----- End Quick Edit -----*****/

$record_id	= getValue("record_id");

//Search data
$id			= getValue("id");
$keyword		= getValue("keyword", "str", "GET", "", 1);
$date			= getValue("date", "dbl");
$show			= getValue("show");
$category	= getValue("category");
$sqlWhere	= " AND pro_last_update < " . (time() - $maxLastUpdate * 86400);
//Tìm theo ID
if($id > 0)			$sqlWhere .= " AND pro_id = " . $id . " ";
//Tìm theo keyword
if($keyword != ""){
	if(validateDate($keyword) == 1){
		$startTime	= convertDateTime($keyword, "00:00:00");
		$endTime		= convertDateTime($keyword, "23:59:59");
		$sqlWhere	.= " AND pro_date >= " . $startTime . " AND pro_date <= " . $endTime . " ";
	}
	else{
		$sqlWhere	.= " AND (pro_name LIKE '%" . $keyword . "%' OR pro_teaser LIKE '%" . $keyword . "%') ";
	}
}
//Tìm theo show
if($show > 0){
	switch($show){
		case 1:	$sqlWhere .= " AND pro_picture <> '' "; break;
		case 2:	$sqlWhere .= " AND pro_picture IS NULL "; break;
		case 3:	$sqlWhere .= " AND pro_active = 1 "; break;
		case 4:	$sqlWhere .= " AND pro_active = 0 "; break;
	}
}
//Tìm theo category
if($category > 0){
	$db_cat	= new db_query("SELECT cat_all_child FROM categories_multi WHERE cat_id = " . $category);
	if($row	= mysql_fetch_assoc($db_cat->result)) $sqlWhere .= " AND cat_id IN (" . $row["cat_all_child"] . ") ";
	unset($db_cat);
}

//Sort data
$sort			= getValue("sort");
switch($sort){
	case 1: $sqlOrderBy = "pro_name ASC"; break;
	case 2: $sqlOrderBy = "pro_name DESC"; break;
	case 3: $sqlOrderBy = "ph_hits ASC"; break;
	case 4: $sqlOrderBy = "ph_hits DESC"; break;
	case 5: $sqlOrderBy = "pro_date ASC"; break;
	case 6: $sqlOrderBy = "pro_date DESC"; break;
	default:$sqlOrderBy = "pro_date DESC"; break;
}

//Get page break params
$page_size		= 50;
$page_prefix	= "Trang: ";
$normal_class	= "page";
$selected_class= "page_current";
$previous		= "<";
$next				= ">";
$first			= "<<";
$last				= ">>";
$break_type		= 1;//"1 => << < 1 2 [3] 4 5 > >>", "2 => < 1 2 [3] 4 5 >", "3 => 1 2 [3] 4 5", "4 => < >"
$url				= getURL(0,0,1,1,"page");
$db_count		= new db_query("SELECT COUNT(*) AS count
										 FROM (categories_multi, " . $fs_table . ") INNER JOIN product_hits ON pro_id = ph_id
									 	 WHERE cat_id = pro_category_id AND cat_id IN (" . $fs_category . ") AND " . $id_field . " <> " . $record_id . " AND categories_multi.lang_id = " . $lang_id . $sqlWhere);
$listing_count	= mysql_fetch_assoc($db_count->result);
$total_record	= $listing_count["count"];
$current_page	= getValue("page", "int", "GET", 1);
if($total_record % $page_size == 0) $num_of_page = $total_record / $page_size;
else $num_of_page = (int)($total_record / $page_size) + 1;
if($current_page > $num_of_page) $current_page = $num_of_page;
if($current_page < 1) $current_page = 1;
$db_count->close();
unset($db_count);
//End get page break params
$db_listing	= new db_query("SELECT *
									 FROM (categories_multi, " . $fs_table . ") INNER JOIN product_hits ON pro_id = ph_id
									 WHERE cat_id = pro_category_id AND cat_id IN (" . $fs_category . ") AND " . $id_field . " <> " . $record_id . " AND categories_multi.lang_id = " . $lang_id . $sqlWhere . "
									 ORDER BY " . $sqlOrderBy . "
									 LIMIT " . ($current_page - 1) * $page_size . ", " . $page_size);
?>
<html>
<head>
<title><?=$fs_title?></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css" media="all">@import "../css/FSportal.css";</style>
<script language="javascript" src="../js/library.js"></script>
<script language="javascript" src="../js/tooltip.js"></script>
</head>
<body>
<div class="bg_title_content">
<div class="content_title" style="float:left"><?=$fs_title?>: <font class="count"><?=format_number($total_record)?></font></div>
<div class="content_title" style="float:right"><a title="Thêm mới" href="add.php?category=<?=$category?>"><img align="absmiddle" border="0" hspace="5" src="<?=$fs_imagepath?>add.gif" />Thêm mới</a></div>
</div>
<div align="center" class="content">
<? //Page break and search data?>
<table width="98%" cellpadding="2" cellspacing="2">
	<tr>
	<?	if($total_record > $page_size){?>
		<td nowrap="nowrap"><?=generatePageBar($page_prefix, $current_page, $page_size, $total_record, $url, $normal_class, $selected_class, $previous, $next, $first, $last, $break_type)?></td>
	<? }?>
		<td align="right">
			<table cellpadding="0" cellspacing="0">
			<form name="search" action="<?=getURL(0,0,1,0)?>" method="get">
				<tr>
					<td class="form_search" nowrap="nowrap">
						ID:
						<input title="ID" type="text" class="form_control" id="id" name="id" value="<?=$id?>" maxlength="11" style="width:80px; text-align:right">&nbsp;
						Từ khóa:
						<input title="Từ khóa" type="text" class="form_control" id="keyword" name="keyword" value="<?=$keyword?>" maxlength="255" style="width:100px">&nbsp;
						<select title="Kiểu hiển thị" name="show" class="form_control">
							<option value="0">--[Tất cả]--</option>
						<?
						$arrShow = array(1 => "Có ảnh", 2 => "Không có ảnh", 3 => "Kích hoạt", 4 => "Không kích hoạt");
						foreach($arrShow as $key => $value){
						?>
							<option title="<?=$value?>" value="<?=$key?>" <? if($key == $show){echo 'selected="selected"';}?>><?=$value?></option>
						<?
						}
						?>
						</select>
						<select title="Hiển thị theo danh mục" name="category" class="form_control">
							<option value="">--[Tất cả các mục]--</option>
						<?
						for($i=0; $i<count($listAll); $i++){
							$db_count	= new db_query("SELECT COUNT(*) AS count FROM " . $fs_table . " WHERE pro_category_id IN (" . $listAll[$i]["cat_all_child"] . ") AND lang_id = " . $lang_id);
							$row = mysql_fetch_assoc($db_count->result);
							unset($db_count);
						?>
							<option title="<?=$listAll[$i]["cat_name"]?> (<?=format_number($row["count"])?>)" value="<?=$listAll[$i]["cat_id"]?>" <? if($listAll[$i]["cat_id"] == $category){echo 'selected="selected"';}?>>
							<?
							for($j=0; $j<$listAll[$i]["level"]; $j++) echo " |--";
							echo " " . $listAll[$i]["cat_name"] . " (" . format_number($row["count"]). ")";
							?>
							</option>
						<?
						}// End for($i=0; $i<count($listAll); $i++)
						?>
						</select>
						<input type="hidden" name="sort" value="<?=$sort?>" />
					</td>
					<td class="form_search" style="padding-left:5px"><input title="Tìm kiếm" type="image" src="<?=$fs_imagepath?>search.gif" border="0"></td>
				</tr>
			</form>
			</table>
		</td>
	</tr>
</table>
<? //End page break and search data?>
<table class="table" border="1" bordercolor="#e5e3e6" cellpadding="3" cellspacing="0" width="98%">
	<tr class="table_title_3">
		<td>Stt.</td>
		<td>Ảnh</td>
		<td>Danh mục</td>
		<td>
			<div>Tên sản phẩm</div>
			<div>
				<?=generate_sort("asc", 1, $sort, $fs_imagepath)?>
				<?=generate_sort("desc", 2, $sort, $fs_imagepath)?>
			</div>
		</td>
		<td nowrap="nowrap">
			<div>Lượt xem</div>
			<div>
				<?=generate_sort("asc", 3, $sort, $fs_imagepath)?>
				<?=generate_sort("desc", 4, $sort, $fs_imagepath)?>
			</div>
		</td>
		<td>
			<div>Cập nhật</div>
			<div>
				<?=generate_sort("asc", 5, $sort, $fs_imagepath)?>
				<?=generate_sort("desc", 6, $sort, $fs_imagepath)?>
			</div>
		</td>
		<td>Thêm<br />ảnh</td>
		<td>Kích<br />hoạt</td>
		<? /*?><td>Lưu</td><? */?>
		<td>Sửa</td>
		<td>Xóa</td>
	</tr>
<?
//Call class form
$form = new form();
$form->class_form_name = "form_name_2";
$form->create_form("quick_edit", $fs_action, "post", "multipart/form-data");
?>
<?
$record_id = getValue("record_id", "int", "POST");
//Đếm số thứ tự
$No = ($current_page - 1) * $page_size;
$startLoop	= $No;
while($listing = mysql_fetch_assoc($db_listing->result)){
	$No++;
	$preview_link	= generate_detail_url($listing["cat_type"], $listing["cat_name"], $listing["pro_name"], $listing["pro_id"]);
?>
	<tr id="tr_<?=$No?>">
		<td class="No"><?=$No?><br /><input type="checkbox" id="check_<?=$No?>" name="record_id[]" value="<?=$listing["pro_id"]?>" onclick="change_bg('check_<?=$No?>', 'tr_<?=$No?>')" /></td>
		<td align="center">
			<div class="image_style">
			<? if($listing["pro_picture"] != ""){?>
				<a href="<?=$preview_link?>" target="_blank" onMouseOver="showtip('<img src=\'<?=$fs_filepath?><?=$listing["pro_picture"]?>\' />')" onMouseOut="hidetip()"><img src="<?=$fs_filepath?>small_<?=$listing["pro_picture"]?>" onError="this.src='<?=$fs_no_image?>'" /></a>
			<? }else{?>
				<a href="<?=$preview_link?>" target="_blank"><img class="style_image" width="40" src="<?=$fs_no_image?>" /></a>
			<? }?>
			</div>
		</td>
		<td align="center">
			<select title="Danh mục tin" id="pro_category_id_<?=$No?>" name="pro_category_id<?=$listing["pro_id"]?>" class="form_control">
				<option value="">--[Danh mục tin]--</option>
			<? for($i=0; $i<count($listAll); $i++){?>
				<option title="<?=$listAll[$i]["cat_name"]?>" value="<?=$listAll[$i]["cat_id"]?>" <? if($listAll[$i]["cat_id"] == $listing["cat_id"]){echo 'selected="selected"';}?>>
				<?
				for($j=0; $j<$listAll[$i]["level"]; $j++) echo " |--";
				echo " " . $listAll[$i]["cat_name"];
				?>
				</option>
			<? }?>
			</select>
			<? if($listing["pro_picture"] != ""){?><div style="margin-top:5px"><a title="<?=$listing["pro_picture_width"] . " x " . $listing["pro_picture_height"]?>" href="javascript:if(confirm('Bạn có muốn xóa ảnh này không?')){window.location.href='delete.php?type=picture&record_id=<?=$listing["pro_id"]?>&redirect=<?=base64_encode($_SERVER["REQUEST_URI"])?>'}">[Xóa ảnh]</a></div><? }?>
		</td>
		<td align="center">
			<?=$form->create_table(2, 2, "");?>
			<?=$form->text("Tên", "pro_name_" . $No, "pro_name" . $listing["pro_id"], $listing["pro_name"], "Tên sản phẩm", 1, 203, "", 255, "", "", "")?>
			<tr>
				<td class="form_name">Giá :</td>
				<td class="form_text">
					<input type="text" class="form_control" id="pro_price_<?=$No?>" name="pro_price<?=$listing["pro_id"]?>" value="<?=$listing["pro_price"]?>" style="text-align: right;; width:90px;" />
					Đv: <input type="text" class="form_control" id="pro_unit_<?=$No?>" name="pro_unit<?=$listing["pro_id"]?>" value="<?=$listing["pro_unit"]?>" style="width:90px;" />
				</td>
			</tr>
			<?=$form->close_table();?>
		</td>
		<td class="hits"><?=number_format($listing["ph_hits"],0,".",",")?></td>
		<td align="right">
			<div><?=date("d/m/Y", $listing["pro_date"])?></div>
			<div style="color:#666666; font-size:10px"><?=date("H:i A", $listing["pro_date"])?></div>
		</td>
		<td align="center"><img title="Thêm ảnh" align="absmiddle" src="<?=$fs_imagepath?>add.gif" style="cursor:pointer" onClick="more_picture('edit', <?=$listing["pro_id"]?>)"></td>
		<td align="center"><a href="quickset.php?type=active&record_id=<?=$listing["pro_id"]?>&redirect=<?=base64_encode($_SERVER["REQUEST_URI"])?>"><img border="0" src="<?=$fs_imagepath?>active_<?=$listing["pro_active"]?>.gif" /></a></td>
		<? /*?><td align="center"><input title="Lưu dữ liệu" type="image" hspace="5" src="<?=$fs_imagepath?>save.gif" onClick="MM_validateForm('pro_category_id_<?=$No?>','','R','pro_name_<?=$No?>','','R'); return document.MM_returnValue;" /></td><? */?>
		<td align="center"><a title="Sửa dữ liệu" href="edit.php?record_id=<?=$listing["pro_id"]?>&redirect=<?=base64_encode($_SERVER["REQUEST_URI"])?>"><img border="0" hspace="5" src="<?=$fs_imagepath?>edit.gif"></a></td>
		<td align="center"><img title="Xóa dữ liệu" hspace="5" src="<?=$fs_imagepath?>/delete.gif" style="cursor:pointer" onClick="if(confirm('Bạn có muốn xóa dữ liệu này không?')){window.location.href='delete.php?record_id=<?=$listing["pro_id"]?>&redirect=<?=base64_encode($_SERVER["REQUEST_URI"])?>'}" /></td>
	</tr>
<?
}// End while($listing = mysql_fetch_assoc($db_listing->result))
?>
</table>
<table width="98%" cellpadding="2" cellspacing="2">
	<tr>
		<td>
			<a class="text_link" href="javascript:;" onclick="check_all(<?=$startLoop?>, <?=$No?>)"><img src="<?=$fs_imagepath?>check_all.gif" style="vertical-align: middle; margin-right:5px;" />Chọn tất cả</a> &nbsp;
			<a class="text_link" href="javascript:;" onclick="uncheck_all(<?=$startLoop?>, <?=$No?>)"><img src="<?=$fs_imagepath?>uncheck_all.gif" style="vertical-align: middle; margin-right:5px;" />Bỏ chọn tất cả</a> &nbsp;
			<input type="submit" class="form_button" value="Cập nhật" style="background:url(<?=$fs_imagepath?>button_3.gif)" />
		</td>
		<? if($total_record > $page_size){?><td><?=generatePageBar($page_prefix, $current_page, $page_size, $total_record, $url, $normal_class, $selected_class, $previous, $next, $first, $last, $break_type)?></td><? }?>
		<td align="right"><a title="Go to top" accesskey="T" class="top" href="#">Lên trên<img align="absmiddle" border="0" hspace="5" src="<?=$fs_imagepath?>top.gif"></a></td>
	</tr>
</table>
<?=$form->hidden("action", "action", "quick_edit", "");?>
<?
$form->close_form();
unset($form);
?>
</div>
</body>
</html>
<script language="javascript">ButtonLeftFrame();</script>